package com.hejia.bulbul.scheduler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

import com.alibaba.fastjson.JSONObject;
import com.hejia.alauda.Constants;
import com.hejia.alauda.entity.Order;
import com.hejia.alauda.service.OrderService;
import com.hejia.alauda.service.PaymentService;
import com.hejia.alauda.utils.LLPayUtil;
import com.yeepay.yjpay.service.PayAPIService;

/**
 * 订单支付状态查询作业，调用第三方支付订单状态查询接口，获取订单支付状态。
 * 
 * @author hyr
 *
 */
public class OrderPayStatusQueryScheduler {

	private static final Log logger = LogFactory.getLog(OrderPayStatusQueryScheduler.class);
	
	@Resource
	private OrderService orderService;
	
	@Resource
	private PaymentService paymentService;
	
	@Resource
	private PayAPIService payAPIService;
	
	/**
	 * 执行订单支付状态查询
	 */
    @Scheduled(fixedDelay = 10 * 60 * 1000)
    @Async("executor")
	public void runOrderPayStatusQuery() {
		
    	try {
    		logger.info("开始执行订单支付状态查询");
    		
    		DateTime startTime = new DateTime();
    		startTime = startTime.minusHours(100);
    		List<Long> orderIds = orderService.findNotSyncPayStatusOrderIds(startTime.toDate());
    		for (Long orderId : orderIds) {
    			Order order = this.orderService.findOrderById(orderId);
    			String payGateStatus = this.queryOrderPayStatus(order);
    			if (payGateStatus == null) {
    				continue;
    			}
    			paymentService.updateOrderPayGateStatus(orderId, payGateStatus);
    		}
    		
    		logger.info("结束执行订单支付状态查询");
    	} catch (Exception e) {
    		logger.error("执行订单支付状态查询异常", e);
    	}
	}
		
	/**
	 * 查询订单支付状态
	 * @param order 订单
	 * @return	订单支付状态
	 */
	private String queryOrderPayStatus(Order order) {
		
		String payStatus = null;
		if(order.getPayGateCode() == null || Constants.PAYGATE_CODE_LLPAY.equals(order.getPayGateCode())){
			JSONObject json = LLPayUtil.orderQuery(order.getPayNumber());
			if(json != null){
				// 支付状态
				Map<String, String> statusMap = new HashMap<>();
				statusMap.put("SUCCESS", "成功");
				statusMap.put("WAITING", "等待支付");
				statusMap.put("PROCESSING", "银行支付处理中");
				statusMap.put("REFUND", "退款");
				statusMap.put("FAILURE", "失败");
				
				payStatus = json.get("result_pay").toString();
			}
			
		}else if(Constants.PAYGATE_CODE_YEEPAY.equals(order.getPayGateCode())){
			try {
				String result = this.payAPIService.queryPay(order.getPayNumber());
				JSONObject json = JSONObject.parseObject(result);
				if(!json.containsKey("error_code")){
					// 支付状态
					Map<String, String> statusMap = new HashMap<>();
					statusMap.put("0", "失败");
					statusMap.put("1", "成功");
					statusMap.put("2", "未处理");
					statusMap.put("3", "处理中");
					
					payStatus = json.get("status").toString();
				}
			} catch (Exception e) {
				logger.error("查询易宝支付交易记录失败", e);
			}
		}
		
		return payStatus;
	}
}
